// stores/userStore.ts
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 从 localStorage 初始化状态
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || null))

  // 计算属性 - 是否已登录
  const isLoggedIn = computed(() => !!userInfo.value?.token)

  // 登录方法
  const setUserInfo = (loginData) => {
    userInfo.value = loginData
    // 保存到 localStorage
    localStorage.setItem('userInfo', JSON.stringify(loginData))
  }

  // 登出方法
  const removeUserInfo = () => {
    userInfo.value = null
    // 清除 localStorage
    localStorage.removeItem('userInfo')
  }

  return {
    userInfo,
    isLoggedIn,
    setUserInfo,
    removeUserInfo
  }
})